const app = getApp();
const { htmlEncode, checkInputCode} = require('../../utils/util.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: app.globalData.baseUrl,
    fileUrl: app.globalData.fileUrl,
    tempFilePaths: '',
    deadlineArray: ['立即', '七天', '十五天', '一个月'],
    riskTypeArray: ['职业卫生', '消防安全', '环境保护', '安防管理', '安全生产'],
    riskLevelArray: ['一般', '重大'],
    deadlineIndex: null,
    riskTypeIndex: null,
    areaIndex: null,
    areaLevel1Index: null,
    areaLevel2Index: null,
    areaLevel3Index: null,
    imgList: [],
    deptList: [],
    areaList: [],
    areaLevel1List: [],
    areaLeve2List: [],
    areaLeve3List: [],
    location: null,
    content: null,
    suggest: null,
    sapId: null,
    bigSearchShow: false,
    bigSearchType: "",
    saferFlag: null,
    dutyDept: "",
    searchDataList: [],
    imgSuccessLoaded:[],
    proposeDept: "",
    proposeByName: ""
  },
  getAllDept: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/deptInfo/wx/getAllDept',
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取所有部门信息:', res.data);
        var data = res.data;
        that.setData({
          deptList: data.data
        })
      }
    });
  },
  riskLevelChange: function (e) {
    console.log('隐患分级选择变化，携带值为', e.detail.value)
    this.setData({
      riskLevelIndex: e.detail.value
    })
  },
  initSapId: function () {
    var userInfo = wx.getStorageSync('userinfo');
    console.log('userInfo', userInfo);
    if (userInfo.siocDepartCode == '应急管理部') {
      this.getAllDept();
    }
    this.setData({
      sapId: userInfo.siocSapNo,
      proposeDept: userInfo.siocDepartCode,
      saferFlag: userInfo.siocDepartCode == '应急管理部' ? true : false,
      proposeByName: userInfo.siocCnName
    })
  },

  deadlineChange: function (e) {
    this.setData({
      deadlineIndex: e.detail.value
    })
  },
  riskTypeChange: function (e) {
    this.setData({
      riskTypeIndex: e.detail.value
    })
  },
  areaChange: function (e) {
    this.setData({
      areaIndex: e.detail.value
    })
    var that = this;
    wx.request({
      url: (that.data.baseUrl + '/areaInfo/wx/getLevel1Area?area=' + that.data.areaList[that.data.areaIndex]).replaceAll('#', '%23'),
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取一级区域信息:', res.data);
        var data = res.data;
        that.setData({
          areaLevel1List: data.data,
          areaLevel1Index: null,
          areaLevel2Index: null,
          areaLevel3Index: null,
        })
      }
    });
  },
  areaLevel1Change: function (e) {
    console.log('一级区域选择改变，携带值为', e)
    this.setData({
      areaLevel1Index: e.detail.value
    })
    var that = this;
    wx.request({
      url: (that.data.baseUrl + '/areaInfo/wx/getLevel2Area?area=' + that.data.areaList[that.data.areaIndex] + '&level1Area=' + that.data.areaLevel1List[that.data.areaLevel1Index].replaceAll('&', '%26')).replaceAll('#', '%23'),
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取二级区域信息:', res.data);
        var data = res.data;
        that.setData({
          areaLevel2List: data.data,
          areaLevel2Index: null,
          areaLevel3Index: null,
        })
      }
    });
  },
  areaLevel2Change: function (e) {
    console.log('二级区域选择改变，携带值为', e)
    this.setData({
      areaLevel2Index: e.detail.value
    })
    var that = this;
    wx.request({
      url: (that.data.baseUrl + '/areaInfo/wx/getLevel3Area?area=' + that.data.areaList[that.data.areaIndex] + '&level1Area=' + that.data.areaLevel1List[that.data.areaLevel1Index].replaceAll('&', '%26') + '&level2Area=' + that.data.areaLevel2List[that.data.areaLevel2Index]).replaceAll('#', '%23'),
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取三级区域信息:', res.data);
        var data = res.data;
        that.setData({
          areaLevel3List: data.data,
          areaLevel3Index: null,
        })
      }
    });
  },
  areaLevel3Change: function (e) {
    console.log('三级区域选择改变，携带值为', e)
    this.setData({
      areaLevel3Index: e.detail.value
    })
  },


  getAllArea: function () {
    var that = this;
    wx.request({
      url: that.data.baseUrl + '/areaInfo/wx/getAllArea',
      method: 'GET',
      header: {
        'Content-Type': 'application/json' // 请求头  
      },
      success(res) {
        console.log('获取所有区域信息:', res.data);
        var data = res.data;
        that.setData({
          areaList: data.data
        })
      }
    });
  },
  submitForm(e) {
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    var that = this;
    const formData = e.detail.value;
    console.log('form发生了submit事件，携带数据为：', formData);
    formData.imgList = that.data.imgList;
    formData.dutyDept = that.data.dutyDept;
    var errMsg = "";
    if (!formData.area) {
      errMsg = errMsg + "隐患区域不能为空;";
    }
    if (!formData.areaLevel1) {
      errMsg = errMsg + "一级区域不能为空;";
    }
    if (!formData.location) {
      errMsg = errMsg + "具体位置不能为空;";
    }
    if (formData.imgList.length < 1) {
      errMsg = errMsg + "隐患图片不能为空;";
    }
    if (!formData.content) {
      errMsg = errMsg + "隐患内容不能为空;";
    }
    if (that.data.saferFlag) {
      if (!formData.deadline) {
        errMsg = errMsg + "整改期限不能为空;";
      }
      if(!formData.dutyDept){
        errMsg = errMsg + "责任部门不能为空;";
      }
    }

    if (!formData.riskType) {
      errMsg = errMsg + "隐患类型不能为空;";
    }
    if (!formData.suggest) {
      errMsg = errMsg + "整改建议不能为空;";
    }

    if(checkInputCode(formData.location)){
      errMsg = errMsg + "位置不允许输入特殊字符;";
    }

    if(checkInputCode(formData.content)){
      errMsg = errMsg + "问题情况不允许输入特殊字符;";
    }

    if(checkInputCode(formData.suggest)){
      errMsg = errMsg + "排查措施不允许输入特殊字符;";
    }

    // for(let i in formData){
    //   formData[i] = htmlEncode(formData[i])
    // }
    if(that.data.imgSuccessLoaded.length>0 && that.data.imgSuccessLoaded.filter(item=>item==0).length>0){
      errMsg = errMsg + "请检查是否上传正确的图片;";
    }
    // if (!formData.riskLevel) {
    //   errMsg = errMsg + "隐患分级不能为空;";
    // }
    console.log('form发生了submit事件，携带数据为：', formData);
    if (errMsg.length > 0) {
      wx.hideLoading()
      wx.showModal({
        title: '提示',
        content: errMsg,
        showCancel: false
      })
      return;
    }

    // 向服务器提交表单数据
    wx.request({
      url: that.data.baseUrl + '/rmStaff/wx/addRmStaff',
      method: 'POST',
      header:{
        'userNo':  wx.getStorageSync('userinfo').siocSapNo // 请求头  
      },
      data: formData,
      success: function (res) {
        wx.hideLoading()
        console.log('表单提交成功', res);
        if (200 == res.data.code) {
          that.setData({
            tempFilePaths: '',
            location: null,
            content: null,
            suggest: null,
            deadlineIndex: null,
            riskTypeIndex: null,
            areaIndex: null,
            areaLevel1Index: null,
            areaLevel2Index: null,
            areaLevel3Index: null
          });
          wx.showModal({
            title: '提示',
            content: res.data.msg,
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/risk-list/risk-list'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          });
        }
      },
      fail: function (err) {
        wx.hideLoading()
        console.error('表单提交失败', err);
        wx.showToast({
          title: '表单提交失败',
          icon: 'none'
        });
      }
    });
  },
  ViewImage(e) {
    let urls = [];
    let current = this.data.fileUrl + e.currentTarget.dataset.url;
    for (let key in this.data.imgList) {
      urls.push(this.data.fileUrl + this.data.imgList[key]);
    };
    wx.previewImage({
      urls: urls,
      current: current
    });
  },
  DelImg(e) {



    wx.showModal({
      title: '删除图片',
      content: '确定要删除这张图片',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.data.imgSuccessLoaded.splice(e.currentTarget.dataset.index, 1);
          
          this.setData({
            imgList: this.data.imgList,
            imgSuccessLoaded:this.data.imgSuccessLoaded
          })
        }
      }
    })
  },


  ChooseImage: function () {
    var that = this;
    wx.chooseMedia({
      count: 1, // 一次只能选择一张图片
      sizeType: ['original', 'compressed'], // 压缩图片
      sourceType: ['album', 'camera'], // 从相册选择
      async success(res) { // 将图片上传到服务器

        wx.uploadFile({
          url: that.data.fileUrl + '/common/picUpload', // 上传的服务器地址
          filePath: res.tempFiles[0].tempFilePath, // 图片的本地地址
          name: 'file', // 服务端用于接收文件的参数名
          success(res) {
            let json = JSON.parse(res.data);
            let tempArray = [];
            tempArray.push(json.fileName);
            // 上传成功，做一些处理
            if (that.data.imgList.length != 0) {
              that.setData({
                imgList: that.data.imgList.concat(tempArray)
              })
            } else {
              that.setData({
                imgList: tempArray
              })
            }
          }
        })
      }
    })
  },

  imageLoad(e){
    

    this.data.imgSuccessLoaded.push(1)
    this.setData({
      imgSuccessLoaded:this.data.imgSuccessLoaded
    })


  },

  imageError(e){

    this.data.imgSuccessLoaded.push(0)
    this.setData({
      imgSuccessLoaded:this.data.imgSuccessLoaded
    })
  },

  doBigSearchShow(e) {
    console.log('e', e);
    const tempArray = [];
    const typeMethods = {
      dept: () => {
        if (this.data.deptList.length == 0) {
          wx.showToast({
            title: '暂无部门指派',
            icon: 'none'
          });
          return;
        } else {
          this.data.deptList.forEach(item => {
            tempArray.push({
              name: item
            });
          });
        }
      }
    }
    typeMethods[e.currentTarget.dataset.type]();

    this.setData({
      bigSearchType: e.currentTarget.dataset.type,
      bigSearchShow: true,
      searchDataList: tempArray
    })
  },
  searchSelect(e) {
    const params = {}
    params['dutyDept'] = e.detail.name

    this.setData({
      ...params
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {

    this.getAllArea();
    this.initSapId();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})